// 获取画布和上下文
const canvas = document.getElementById('game-canvas');
const ctx = canvas.getContext('2d');

// 画布尺寸
const CANVAS_WIDTH = 800;
const CANVAS_HEIGHT = 600;
canvas.width = CANVAS_WIDTH;
canvas.height = CANVAS_HEIGHT;

// 得分
let score = 0;
const scoreElement = document.getElementById('score');

// 鱼的数组
let fishes = [];

// 子弹的数组
let bullets = [];

// 鱼的构造函数
function Fish() {
    this.x = CANVAS_WIDTH;
    this.y = Math.random() * CANVAS_HEIGHT;
    this.speed = Math.random() * 3 + 1;
    this.width = 50;
    this.height = 30;
    this.color = 'orange';
}

// 子弹的构造函数
function Bullet(x, y) {
    this.x = x;
    this.y = y;
    this.speed = 10;
    this.width = 5;
    this.height = 5;
    this.color = 'red';
}

// 绘制鱼
function drawFish(fish) {
    ctx.beginPath();
    ctx.fillStyle = fish.color;
    ctx.fillRect(fish.x, fish.y, fish.width, fish.height);
    ctx.closePath();
}

// 绘制子弹
function drawBullet(bullet) {
    ctx.beginPath();
    ctx.fillStyle = bullet.color;
    ctx.fillRect(bullet.x, bullet.y, bullet.width, bullet.height);
    ctx.closePath();
}

// 移动鱼
function moveFish() {
    for (let i = fishes.length - 1; i >= 0; i--) {
        const fish = fishes[i];
        fish.x -= fish.speed;
        if (fish.x + fish.width < 0) {
            fishes.splice(i, 1);
        }
    }
}

// 移动子弹
function moveBullet() {
    for (let i = bullets.length - 1; i >= 0; i--) {
        const bullet = bullets[i];
        bullet.x += bullet.speed;
        if (bullet.x > CANVAS_WIDTH) {
            bullets.splice(i, 1);
        }
    }
}

// 检查碰撞
function checkCollision() {
    for (let i = fishes.length - 1; i >= 0; i--) {
        const fish = fishes[i];
        for (let j = bullets.length - 1; j >= 0; j--) {
            const bullet = bullets[j];
            if (
                bullet.x < fish.x + fish.width &&
                bullet.x + bullet.width > fish.x &&
                bullet.y < fish.y + fish.height &&
                bullet.y + bullet.height > fish.y
            ) {
                // 发生碰撞，移除鱼和子弹
                fishes.splice(i, 1);
                bullets.splice(j, 1);
                score += 10;
                scoreElement.textContent = score;
                break;
            }
        }
    }
}

// 创建鱼
function createFish() {
    if (Math.random() < 0.02) {
        fishes.push(new Fish());
    }
}

// 发射子弹
function shootBullet() {
    const bullet = new Bullet(0, CANVAS_HEIGHT / 2);
    bullets.push(bullet);
}

// 主游戏循环
function gameLoop() {
    ctx.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);

    createFish();
    moveFish();
    moveBullet();
    checkCollision();

    fishes.forEach(drawFish);
    bullets.forEach(drawBullet);

    requestAnimationFrame(gameLoop);
}

// 鼠标点击发射子弹
canvas.addEventListener('click', shootBullet);

// 开始游戏循环
gameLoop();